package com.dm.hdfxxt.common;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class GetCustomIp {
    /**
     * 得到访问者的IP地址
     * @return ip
     * @throws Exception
     */
    public String getIp(HttpServletRequest request) throws Exception{
        String ip = request.getHeader("X-Forwarded-For");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = ip.indexOf(",");
            if(index != -1){
                return ip.substring(0,index);
                }else{
                return ip;
                }
            }
        ip = request.getHeader("X-Real-IP");
        if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
            return ip;
            }
         return request.getRemoteAddr();
    }

}
